package com.shujia.mr.wc1;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;

/**
 * reduce的计算逻辑是在拉取完小文件并且归并排序后进行的，reduce逻辑是作用在相同的键分组上
 * 我们只需要关心，输入的类型和输出的类型以及reduce要处理的逻辑
 */
public class MyReducer extends Reducer<Text, LongWritable, Text, LongWritable> {
    //重写reduce逻辑，处理一个键对应的迭代器数据
    //<键, [xx,xx,xx,xx,xx]>
    //<"hello",[1,1,1,1,1,...]> --> <"hello", 3>

    @Override
    protected void reduce(Text key, Iterable<LongWritable> values, Reducer<Text, LongWritable, Text, LongWritable>.Context context) throws IOException, InterruptedException {
        long sum = 0L;

        for (LongWritable value : values) {
            sum += value.get();
        }

        //将最终的结果写入到文件中
        context.write(key, new LongWritable(sum));
    }
}
